package com.se.aiClient;

import com.se.common.AIErrorType;
import com.se.exception.AIException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class AIClient {
    private static final String AI_ENDPOINT = "http://localhost:8081/ai/generate";
    private static final String AI_STREAM_ENDPOINT = "http://localhost:8081/ai/generateStream";
    private static final Logger logger = LoggerFactory.getLogger(AIClient.class);
    private static final HttpClient client = HttpClient.newHttpClient();

    public String generate(String prompt, boolean chatOrExplain) throws IOException, InterruptedException, AIException{

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(AI_ENDPOINT))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(prompt))
                .build();

        HttpResponse<String> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofString()
        );

        if(response.statusCode() == 400) {
            if(response.body().contains(AIErrorType.UNAUTHORIZED_ERROR)){
                throw new AIException("APIKEY不正确！", AIErrorType.UNAUTHORIZED_ERROR);
            }
            else if(response.body().contains(AIErrorType.NOT_ENOUGH_TOKEN)){
                throw new AIException("余额不足！", AIErrorType.NOT_ENOUGH_TOKEN);
            }
            else if(response.body().contains(AIErrorType.SERVER_ERROR)){
                throw new AIException("服务器异常！", AIErrorType.SERVER_ERROR);
            }
            else if(response.body().contains(AIErrorType.SERVER_BUSY)){
                throw new AIException("服务器繁忙！", AIErrorType.SERVER_BUSY);
            }
            else{
                throw new AIException("未知错误！", AIErrorType.UNKNOWN_ERROR);
            }
        }
        JSONObject json = new JSONObject(String.valueOf(response.body()));
        String text = json.getString("generation");
        if(chatOrExplain) {
            return AIClientUtils.getCleanedString(text);
        }
        else {
            return text;
        }
    }
}
